import axios from 'axios';

// 创建 axios 实例
const api = axios.create({
  // 根据实际部署情况设置基础URL
  baseURL: 'http://116.63.51.45:30180',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
  }
});

// 请求拦截器
api.interceptors.request.use(
  config => {
    // 可以在这里添加认证信息等
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

// 响应拦截器
api.interceptors.response.use(
  response => {
    // 确保返回数据格式正确
    const data = response.data;

    // 处理服务请求的特殊情况
    if (response.config.url && response.config.url.includes('/requests')) {
      // 确保请求数据格式正确
      if (data && typeof data === 'object') {
        return {
          ingress: Array.isArray(data.ingress) ? data.ingress : [],
          egress: Array.isArray(data.egress) ? data.egress : []
        };
      }
      // 如果数据格式不正确，返回空数组
      return { ingress: [], egress: [] };
    }

    return data;
  },
  error => {
    // 统一处理错误
    const { response } = error;
    if (response) {
      // 服务器返回了错误状态码
      console.error(`请求错误: ${response.status}`, response.data);

      // 可以根据不同的状态码做不同的处理
      switch (response.status) {
        case 401:
          // 未授权处理
          break;
        case 403:
          // 禁止访问处理
          break;
        case 404:
          // 资源不存在处理
          break;
        case 500:
          // 服务器错误处理
          break;
      }
    } else {
      // 网络错误或请求被取消
      console.error('网络错误或请求被取消');
    }

    return Promise.reject(error);
  }
);

// 服务相关API
export const servicesApi = {
  getAll: () => api.get('/api/services'),
  getById: (id: string) => api.get(`/api/services/${id}`),
  getMetrics: (id: string) => api.get(`/api/services/${id}/metrics`),
};

// 链路追踪相关API
export const tracesApi = {
  getAll: (params?: any) => api.get('/api/traces', { params }),
  getById: (id: string) => api.get(`/api/traces/${id}`),
  getServices: (traceId: string) => api.get(`/api/traces/${traceId}/services`),
  getTopology: (traceId: string) => api.get(`/api/traces/${traceId}/topology`),
  getServiceRequests: (serviceId: string) => api.get(`/api/traces/services/${serviceId}/requests`),
  create: (data: any) => api.post('/api/traces', data),
  delete: (id: string) => api.delete(`/api/traces/${id}`),
};

// 记录管理相关API
export const recordApi = {
  // 记录服务管理
  getServices: (params?: any) => api.get('/api/record/services', { params }),
  getServiceById: (id: string) => api.get(`/api/record/services/${id}`),
  createService: (data: any) => api.post('/api/record/services', data),
  updateService: (id: string, data: any) => api.put(`/api/record/services/${id}`, data),
  deleteService: (id: string) => api.delete(`/api/record/services/${id}`),

  // 请求记录管理
  getRequests: (params?: any) => api.get('/api/record/requests', { params }),
  getRequestById: (id: string) => api.get(`/api/record/requests/${id}`),
  deleteRequest: (id: string) => api.delete(`/api/record/requests/${id}`),
  convertToDefinition: (id: string) => api.get(`/api/record/requests/${id}/convert`),

  // 记录控制
  startRecording: (data: any) => api.post('/api/record/start', data),
  stopRecording: () => api.post('/api/record/stop'),
  getRecordStatus: () => api.get('/api/record/status')
};

// 请求管理相关API
export const requestApi = {
  // 请求定义管理
  getDefinitions: (params?: any) => api.get('/api/request/definitions', { params }),
  getDefinitionById: (id: string) => api.get(`/api/request/definitions/${id}`),
  createDefinition: (data: any) => api.post('/api/request/definitions', data),
  updateDefinition: (id: string, data: any) => api.put(`/api/request/definitions/${id}`, data),
  deleteDefinition: (id: string) => api.delete(`/api/request/definitions/${id}`),
  executeDefinition: (id: string) => api.post(`/api/request/definitions/${id}/execute`)
};

// 拦截管理相关API
export const interceptApi = {
  // 拦截控制
  startIntercept: (data: any) => api.post('/api/request/intercept/start', data),
  stopIntercept: (data: any) => api.post('/api/request/intercept/stop', data),
  getInterceptRules: () => api.get('/api/request/intercept/list'),
  clearInterceptRules: () => api.post('/api/request/intercept/clear')
};

// 故障注入相关API
export const faultsApi = {
  getAll: () => api.get('/api/faults'),
  getById: (id: string) => api.get(`/api/faults/${id}`),
  create: (data: any) => api.post('/api/faults', data),
  update: (id: string, data: any) => api.put(`/api/faults/${id}`, data),
  delete: (id: string) => api.delete(`/api/faults/${id}`),
  activate: (id: string) => api.post(`/api/faults/${id}/activate`),
  deactivate: (id: string) => api.post(`/api/faults/${id}/deactivate`),
};

// 系统相关API
export const systemApi = {
  getHealth: () => api.get('/health'),
  getStats: () => api.get('/api/stats'),
  getSettings: () => api.get('/api/settings'),
  updateSettings: (data: any) => api.put('/api/settings', data),
};

export default api;
